package com.ck.core.util;

import com.ck.core.constant.CharsetConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件工具类
 *
 * @author dxy
 * @date 2018/7/3 14:07
 */
public class FileUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
    /**
     * 读取文件
     *
     * @param path 路径
     * @return
     */
    public static String readFile(String path) {
        StringBuffer laststr = new StringBuffer("");
        File file = new File(path);// 打开文件
        BufferedReader reader = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in, CharsetConstant.UTF8));// 读取文件
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr.append(tempString);
            }
            reader.close();
            in.close();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException el) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException el) {
                }
            }
        }
        return laststr.toString();
    }

    /**
     * MultipartFile转化为File
     *
     * @param multipartFile MultipartFile
     * @return File
     * @throws IOException
     */
    public static File multipartFileConvertFile(MultipartFile multipartFile) throws IOException {
        if (multipartFile == null) {
            throw new NullPointerException("文件不能为空");
        }
        File file = new File(multipartFile.getOriginalFilename());
        if (!file.createNewFile()) {
            logger.warn("multipartFileConvertFile.文件删除失败");
        }
        //自动关闭流
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        return file;
    }

    /**
     * MultipartFile转化为File
     *
     * @param multipartFile MultipartFile
     * @return File
     * @throws IOException
     */
    public static File multipartFileConvertFile(MultipartFile multipartFile, String fileName) throws IOException {
        if (multipartFile == null) {
            throw new NullPointerException("文件不能为空");
        }
        File file = null;
        if (fileName != null && fileName != "") {
            file = new File(fileName);
        } else {
            file = new File(multipartFile.getOriginalFilename());
        }
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        return file;
    }


    /**
     * 获取文件MD5值
     *
     * @param file File
     * @return String
     */
    public static String getFileMD5(File file) {
        String md5 = "";
        if (file.exists() && file.isFile()) {
            try ( InputStream in = new FileInputStream(file)){
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] buffer = new byte[1024];
                int read;
                while ((read = in.read(buffer)) != -1) {
                    md.update(buffer, 0, read);
                }
                byte[] data = md.digest();
                md5 = byteToHex(data);
            } catch (NoSuchAlgorithmException e) {
                logger.error(e.getMessage(),e);
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
        return md5;
    }

    /**
     * byte转化为16进制字符串
     *
     * @param bytes byte[]
     * @return String
     */
    private static String byteToHex(byte[] bytes) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuffer stringbuffer = new StringBuffer(2 * bytes.length);
        for (byte b : bytes) {
            char c0 = hexDigits[b >>> 4 & 0xf];
            char c1 = hexDigits[b & 0xf];
            stringbuffer.append(c0);
            stringbuffer.append(c1);
        }
        return stringbuffer.toString();
    }

    /**
     * TODO 读取文件(导入JSON文件发布广告测试)
     *
     * @param multipartFile
     * @return
     */
    public static String readFile(MultipartFile multipartFile) throws IOException {
        StringBuffer laststr = new StringBuffer("");
//		File file = multipartFileConvertFile(multipartFile);
        File file = new File(multipartFile.getOriginalFilename());
        //自动关闭流
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        BufferedReader reader = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in, CharsetConstant.UTF8));// 读取文件
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr.append(tempString);
            }
            reader.close();
            in.close();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException el) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException el) {
                }
            }
            if (null != file) {
                if ( !file.delete() ) {
                    logger.warn("readFile.文件删除失败");
                }
            }
        }
        return laststr.toString();
    }

    /**
     * 从网路地址中获取文件
     *
     * @param downloadStie 下载地址
     * @param dest         文件存储全路径
     * @throws IOException
     */
    public static void downloadFileFromURL(String downloadStie, String dest) throws IOException {
        if (StringUtils.isBlank(downloadStie) || StringUtils.isBlank(dest)) {
            throw new NullPointerException("");
        }
        File tempFile = new File(dest);
        //如果文件父目录不存在，就创建文件父目录
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
            System.out.println("创建文件夹：" + dest);
        }
        URL url = new URL(downloadStie);
        try (ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }
    }


    /**
     * 删除路径下所有文件
     *
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (!file.isDirectory()) {
            return false;
        }
        String[] tempList = file.list();
        File temp = null;
        for (String aTempList : tempList) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + aTempList);
            } else {
                temp = new File(path + File.separator + aTempList);
            }
            if (temp.isFile()) {
                if (!temp.delete()) {
                    logger.warn("delAllFile.文件删除失败");
                }
            }
            if (temp.isDirectory()) {
                //先删除文件夹里面的文件
                delAllFile(path + "/" + aTempList);
                //再删除空文件夹
                delFolder(path + "/" + aTempList);
                flag = true;
            }
        }
        flag = file.delete();
        return flag;
    }

    private static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath);
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            //删除空文件夹
            if (!myFilePath.delete()) {
                logger.warn("delFolder.文件删除失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 下载文件(写入响应流)
     *
     * @param url      文件地址
     * @param fileName 下载后存储的文件名
     * @param response 响应
     * @return
     */
    public static boolean downloadByUrl(String url, String fileName, HttpServletResponse response) {
        try {
            //获取容器资源解析器
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(url);
            if (resources.length == 0) {
                return false;
            }
            BufferedInputStream br = new BufferedInputStream(resources[0].getInputStream());
            byte[] buf = new byte[1024];
            int len = 0;
            String name = StringUtils.isBlank(fileName) ? resources[0].getFilename() : fileName;
            // 非常重要
            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, CharsetConstant.UTF8));
            OutputStream out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            br.close();
            out.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 通过网络url返回InputStream
     * @param path
     * @return
     */
    public static InputStream returnBitMap(String path) {
        if(StringUtils.isBlank(path)){
            return null;
        }
        URL url = null;
        InputStream is =null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            logger.error(e.getMessage(),e);
        }
        try {
            //利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            if (url == null) {
                return null;
            }
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            //得到网络返回的输入流
            is = conn.getInputStream();

        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return is;
    }

    public static boolean delFile(String path) {
        if(StringUtils.isBlank(path)){
            return false;
        }
        File file = new File(path);
        return file.exists() && file.delete();
    }
}
